package com.combetter.changxing.ui.fragment;

import android.Manifest;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import com.clj.fastble.BleManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.R;
import com.combetter.changxing.bluetooth.FacilityClient2;
import com.combetter.changxing.databinding.FragmentHomeBinding;
import com.combetter.changxing.db.AppDatabase;
import com.combetter.changxing.db.entity.Collect;
import com.combetter.changxing.db.entity.User;
import com.combetter.changxing.model.EventMessage;
import com.combetter.changxing.ui.activity.SecondActivity;
import com.combetter.changxing.ui.base.BaseFragment;
import com.combetter.changxing.util.Check;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.HomeViewModel;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

/**
 * 首页Fragment
 * <p>
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/7.
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomeViewModel> {
    private static int REQUEST_CODE = 100;
    private RxPermissions rxPermissions;
    String preheatTime;
    String preheatTemperature;
    String heatTime;
    String heatTemperature;

    @Override
    public int setLayout() {
        EventBus.getDefault().register(this);
        return R.layout.fragment_home;
    }

    @Override
    public void init() {
        mBinding.tvPercent.bringToFront();
        mBinding.battery.setPower(0);
        mBinding.tvPercent.setText("");
        rxPermissions = new RxPermissions(getActivity());
    }


    @Override
    public Class createViewModel() {
        return HomeViewModel.class;
    }

    @Override
    public void loadData() {
        //获取当前品牌香烟
//        mViewModel.insertSmoke();
        sendCode();
        RxView.clicks(mBinding.codeLayout)
                .compose(rxPermissions.ensure(Manifest.permission.CAMERA))
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Intent intent = new Intent(getActivity(), SecondActivity.class);
                        startActivityForResult(intent, REQUEST_CODE);
                    } else {
                        ToastUtils.error("没有开启相机权限");
                    }
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (FacilityClient2.getClient().bleDevices == null) return;
            if (BleManager.getInstance().isConnected(FacilityClient2.getClient().bleDevices)) {
                FacilityClient2.getClient().getElectric();
            }
            if (BleManager.getInstance().isConnected(FacilityClient2.getClient().bleDevices)) {
                new Handler().postDelayed(() -> FacilityClient2.getClient().getPreheatDate(), 500);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtil.e("解析结果:" + result);
                    mViewModel.selectSmokeMessage(getActivity(), result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    LogUtil.e("解析二维码失败");
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventData(EventMessage message) {
        switch (message.getType()) {
            /**
             *  切换品牌香烟
             */
            case "cutCigarette":
                sendCode();
//                mViewModel.insertSmoke();
                break;

            /**
             *  获取电量
             */
            case "battery":
                setElectric();
//                mBinding.btnAuth.setVisibility(View.VISIBLE);
                break;
            /**
             *  获得设备香烟抽吸数据
             */
            case "CigaretteData":
                Map<String, String> map = (Map<String, String>) message.getData();
                mViewModel.addSmokeCount(map);
                sendCode();
//                mViewModel.insertSmoke();
                break;
            case "timeTemperature":
                setTimeTemperature();
                break;
            case "onDisConnected":
//                mBinding.btnAuth.setVisibility(View.GONE);
                setTimeTemperature();
                setElectric();
                break;
        }
    }

    /**
     * 设置时间，温度
     */
    private void setTimeTemperature() {
        try {
            User user = MyApp.getInstance().getUserInfo();
            if (user != null && !TextUtils.isEmpty(user.getPreheatingTime()) && FacilityClient2.mConnectState == BluetoothGatt.STATE_CONNECTED) {
                preheatTime = String.format(getString(R.string.preheat_time), user.getPreheatingTime());
                preheatTemperature = String.format(getString(R.string.preheat_temperature), user.getPreheatingTemperature());
                heatTime = String.format(getString(R.string.heat_time), user.getHeatingTime());
                heatTemperature = String.format(getString(R.string.heat_temperature), user.getHeatingTemperature());
            } else {
                preheatTime = String.format(getString(R.string.preheat_time), "0");
                preheatTemperature = String.format(getString(R.string.preheat_temperature), "0");
                heatTime = String.format(getString(R.string.heat_time), "0");
                heatTemperature = String.format(getString(R.string.heat_temperature), "0");
            }
            mBinding.tvPreheatTime.setText(preheatTime);
            mBinding.tvPreheatTemperature.setText(preheatTemperature);
            mBinding.tvHeatTime.setText(heatTime);
            mBinding.tvHeatTemperature.setText(heatTemperature);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置电量
     */
    private void setElectric() {
        Integer quantity = MyApp.getInstance().getUserInfo().getElectricQuantity();
        if (quantity != null) {
            mBinding.battery.setPower(quantity);
            if (quantity == 0) {
                mBinding.tvPercent.setText("");
            } else {
                mBinding.tvPercent.setText(quantity + "%");
            }
        } else {
            mBinding.battery.setPower(0);
            mBinding.tvPercent.setText("");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        sendCode();
    }

    private void sendCode() {
        AppDatabase database = MyApp.getInstance().getDatabase();
        if (database.collectDao() != null && database.collectDao().getCollectInfoList() != null && database.collectDao().getCollectInfoList().size() > 0) {
            Collect selectCollect = database.collectDao().findCollect(1);
            if (selectCollect == null||TextUtils.isEmpty( selectCollect.getGoodsName())) {
                return;
            }
            int position = selectCollect.getGoodsName().indexOf("_");
            if (position != -1) {
                String brand2 = selectCollect.getGoodsName().substring(0, position);
                String model2 = selectCollect.getGoodsName().substring(position + 1, selectCollect.getGoodsName().length());
                mViewModel.brand.set(brand2);
                mViewModel.model.set(model2);
            }
            if (!Check.isEmpty(selectCollect.getSindex()) && !Check.isEmpty(selectCollect.getTrademark())) {
                int yid1 = Integer.parseInt(selectCollect.getSindex().substring(0, 2));
                int yid2 = Integer.parseInt(selectCollect.getSindex().substring(2, 4));
                byte[] data0 = new byte[]{(byte) yid1, (byte) yid2};
//                            byte[] data = ByteUtils.addBytes(data0,smoke.getTrademark().getBytes());
                LogUtil.e("----: getTrademark: " + selectCollect.getTrademark());//Marlboro_Balance
//                            LogUtil.e("----: bef: "+ByteUtils.printBytes(data));
                FacilityClient2.getClient().cutCmoke(data0, selectCollect.getTrademark().getBytes());
            }
        } else {
            mViewModel.brand.set("暂无数据");
            mViewModel.model.set("暂无数据");
        }
    }
}